<template>
  <div>

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="12">
            <a-form-item :label="$t('m.system.user.entity.username')">
              <a-input placeholder="" v-model="queryParam.username$lk"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item :label="$t('m.system.user.entity.realname')">
              <a-input placeholder="" v-model="queryParam.realname$lk"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item :label="$t('m.system.user.entity.phone')">
              <a-input placeholder="" v-model="queryParam.phone$lk"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('m.common.button.query') }}</a-button>
              <a-button type="default" @click="searchReset" icon="reload" style="margin-left: 8px">{{ $t('m.common.button.reset') }}</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator" style="border-top: 5px">
      <a-button @click="handleAdd" v-has="'system:SysUser:add'" type="primary" icon="plus">{{ $t('m.common.button.add') }}</a-button>
      <a-button @click="batchDel" v-has="'system:SysUser:delete'" type="default" icon="delete" v-test>{{ $t('m.common.button.delete') }}</a-button>
      <a-button v-if="portal == '0'" v-has="'system:SysUser:export'" type="default" icon="download"
                @click="handleExportXls($t('m.system.user.other.export_filename'))">{{ $t('m.common.button.export') }}</a-button>
      <a-upload v-if="portal == '0'" name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader"
                :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="default" v-has="'system:SysUser:import'" icon="import">{{ $t('m.common.button.import') }}</a-button>
      </a-upload>
      <a-button type="default" v-has="'system:SysUser:frozen'" icon="lock" @click="batchFrozen('2')" v-test>{{$t('m.system.user.other.frozen')}}</a-button>
      <a-button type="default" v-has="'system:SysUser:frozen'" icon="unlock" @click="batchFrozen('1')">{{$t('m.system.user.other.unfrozen')}}</a-button>
      <a-button type="default" icon="hdd" @click="recycleBinVisible=true">{{$t('m.system.user.other.recycle')}}</a-button>
      <a-dropdown v-has="'system:SysUser:add'" v-if="showDingtalk">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="syncUserToDingtalk"><a-icon type="plus" />{{$t('m.system.user.other.syncDingTalkToRemote')}}</a-menu-item>
          <a-menu-item key="2" @click="syncUserToLocal"><a-icon type="plus" />{{$t('m.system.user.other.syncDingTalkFromRemote')}}</a-menu-item>
        </a-menu>
        <a-button icon="plus">{{$t('m.system.user.other.syncDingTalk')}}<a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>

      <a-table
        ref="table"
        bordered
        size="middle"
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">
        <template slot="serialNum" slot-scope="text,record,index">
          {{(ipagination.current-1) * ipagination.pageSize + parseInt(index) + 1}}
        </template>
        <template slot="avatarslot" slot-scope="text, record, index">
          <div class="anty-img-wrap">
            <a-avatar shape="square" :src="getAvatarView(record.avatar)" icon="user"/>
          </div>
        </template>

        <span slot="action" slot-scope="text, record">
         <!-- <a @click="handleEdit(record)" v-has="'user:edit'">{{ $t('m.common.button.update') }}</a>-->
          <a v-has="'system:SysUser:edit'" @click="handleEdit(record)">{{ $t('m.common.button.update') }}</a>
          <a-divider type="vertical"/>
          <a-dropdown>
            <a class="ant-dropdown-link">
              {{$t('m.common.button.more')}} <ych-icon type="down"/>
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a href="javascript:;" @click="handleDetail(record)">{{$t('m.common.title.detail')}}</a>
              </a-menu-item>

              <a-menu-item>
                <a href="javascript:;" v-has="'system:SysUser:changePassword'"
                   @click="handleChangePassword(record.username)" v-test>{{$t('m.system.user.other.changepwd')}}</a>
              </a-menu-item>

              <a-menu-item>
                <a-popconfirm :title="$t('m.common.tip.delete_confirm')" v-has="'system:SysUser:delete'" @confirm="() => handleDelete(record.id)" v-test>
                  <a>{{ $t('m.common.button.delete') }}</a>
                </a-popconfirm>
              </a-menu-item>

              <a-menu-item v-if="record.status==1">
                <a-popconfirm :title="$t('m.system.user.verify.confirmfrozen')" v-has="'system:SysUser:frozen'"
                              @confirm="() => handleFrozen(record.id,2,record.username)" v-test>
                  <a>{{$t('m.system.user.other.frozen')}}</a>
                </a-popconfirm>
              </a-menu-item>

              <a-menu-item v-if="record.status==2">
                <a-popconfirm :title="$t('m.system.user.verify.confirmunfrozen')" v-has="'system:SysUser:frozen'"
                              @confirm="() => handleFrozen(record.id,1,record.username)">
                  <a>{{$t('m.system.user.other.unfrozen')}}</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>
    <!-- table区域-end -->

    <user-modal ref="modalForm" @ok="modalFormOk" :portal="portal"></user-modal>

    <password-modal ref="passwordmodal" @ok="passwordModalOk"></password-modal>

    <!-- 用户回收站 -->
    <user-recycle-bin-modal :visible.sync="recycleBinVisible" @ok="modalFormOk"/>

  </div>
</template>

<script>

  import UserModal from './modules/UserModal'
  import PasswordModal from './modules/PasswordModal'
  import { putAction, getFileAccessHttpUrl, postAction } from '@/api/manage'
  import { frozenBatch } from '@/api/api'
  import { YcListMixin } from '@/mixins/YcListMixin'
  import UserRecycleBinModal from './modules/UserRecycleBinModal'
  import YchConstant from '@/api/YchConstant'
  import config from '@/settings'

  export default {
    name: 'UserSubList',
    mixins: [YcListMixin],
    props: {
      portal: {
        type: String,
        default: '0'
      },
      deptId: String
    },
    components: {
      UserModal,
      PasswordModal,
      UserRecycleBinModal,
    },
    data() {
      return {
        showDingtalk: config.showDingtalk,
        disableMixinCreated: true,
        description: '用户管理',
        queryParam: {},
        recycleBinVisible: false,
        handoverWorkFromUser:'',
        columns: [
          {
            title: this.$t('m.system.user.entity.username'),
            align: 'center',
            dataIndex: 'username',
            width: 120,
            ellipsis: true,
          },
          {
            title: this.$t('m.system.user.entity.realname'),
            align: 'center',
            dataIndex: 'realname',
            ellipsis: true,
          },
          {
            title: this.$t('m.system.user.entity.sex'),
            align: 'center',
            width: 60,
            dataIndex: 'sex_dictText',
          },
          {
            title: this.$t('m.system.user.entity.phone'),
            align: 'center',
            width: 100,
            dataIndex: 'phone',
            ellipsis: true,
          },
          {
            title: this.$t('m.system.user.entity.email'),
            align: 'center',
            width: 100,
            dataIndex: 'email',
            ellipsis: true,
          },
          {
            title: this.$t('m.system.user.entity.workNo'),
            align: 'center',
            width: 80,
            dataIndex: 'workNo'
          },
          {
            title: this.$t('m.system.user.entity.status'),
            align: 'center',
            width: 60,
            dataIndex: 'status_dictText'
          },
          {
            title: this.$t('m.common.label.operate'),
            dataIndex: 'action',
            scopedSlots: { customRender: 'action' },
            align: 'center',
            width: 150
          }
        ],
        url: {
          listInit: YchConstant.PREFIX_SYSTEM + '/user/list?portal=' + this.portal,
          list: null,
          delete: YchConstant.PREFIX_SYSTEM + '/user/delete',
          deleteBatch: YchConstant.PREFIX_SYSTEM + '/user/deleteBatch',
          exportXlsUrl: YchConstant.PREFIX_SYSTEM + '/user/exportExcel',
          importExcelUrl: YchConstant.PREFIX_SYSTEM + '/user/importExcel',
          syncUserToDingtalk: YchConstant.PREFIX_SYSTEM + '/sync/dingtalk/syncUserToDingtalk',
          syncUserToLocal: YchConstant.PREFIX_SYSTEM + '/sync/dingtalk/syncUserToLocal',
        }
      }
    },
    computed: {
      importExcelUrl: function() {
        return `${bootConfig[process.env.NODE_ENV].VUE_APP_API}${this.url.importExcelUrl}`
      }
    },
    methods: {
      getAvatarView: function(avatar) {
        return getFileAccessHttpUrl(avatar)
      },
      batchFrozen: function(status) {
        if (this.selectedRowKeys.length <= 0) {
          this.messageUtil.warning(this.$t('m.common.tip.select_one_warn'))
          return false
        } else {
          let ids = ''
          let that = this
          let isAdmin = false
          that.selectionRows.forEach(function(row) {
            if (row.username == 'admin') {
              isAdmin = true
            }
          })
          if (isAdmin) {
            that.messageUtil.warning(this.$t('m.system.user.verify.isadmin_warn'))
            return
          }
          that.selectedRowKeys.forEach(function(val) {
            ids += val + ','
          })
          var tip = this.$t('m.system.user.verify.confirmfrozen');
          if(status==1){
            tip = this.$t('m.system.user.verify.confirmunfrozen');
          }
          that.$confirm({
            title: that.$t('m.common.title.operate'),
            content: tip,
            onOk: function() {
              frozenBatch({ ids: ids, status: status }).then((res) => {
                if (res.success) {
                  that.messageUtil.success(res.message)
                  that.loadData()
                  that.onClearSelected()
                } else {
                  that.messageUtil.warning(res.message)
                }
              })
            }
          })
        }
      },
      handleFrozen: function(id, status, username) {
        let that = this
        //TODO 后台校验管理员角色
        if ('admin' == username) {
          that.messageUtil.warning(this.$t('m.system.user.verify.isadmin_warn'))
          return
        }
        frozenBatch({ ids: id, status: status }).then((res) => {
          if (res.success) {
            that.messageUtil.success(res.message)
            that.loadData()
          } else {
            that.messageUtil.warning(res.message)
          }
        })
      },
      handleChangePassword(username) {
        this.$refs.passwordmodal.show(username)
      },
      passwordModalOk() {
        //TODO 密码修改完成 不需要刷新页面，可以把datasource中的数据更新一下
      },
      syncUserToDingtalk() {
        let url = this.url.syncUserToDingtalk
        let selectedRowKeys = this.selectedRowKeys
        this.synDingTalk(url,selectedRowKeys)
      },
      syncUserToLocal() {
        let url = this.url.syncUserToLocal
        this.synDingTalk(url,[])
      },
      synDingTalk(url,selectedRowKeys){
        let content = this.$t('m.system.user.verify.synDingtalkUserConfirm')
        if (Array.isArray(selectedRowKeys) && selectedRowKeys.length > 0) {
          content = this.$t('m.system.user.verify.synSelectDingtalkUserConfirm',[selectedRowKeys.length])
        } else {
          selectedRowKeys = []
        }
        return new Promise((resolve, reject) => {
          let model = this.$confirm({
            title: this.$t('m.system.user.other.synDingTalkTitle'),
            content,
            onOk: () => {
              model.update({
                keyboard: false,
                okText: this.$t('m.system.user.other.synDingTalkTips'),
                cancelButtonProps: {props: {disabled: true}}
              })
              return postAction(url, {
                ids: selectedRowKeys.join(',')
              }).then(res => {
                let options = null
                if (res.result) {
                  options = {
                    width: 600,
                    title: res.message,
                    content: (h) => {
                      let nodes
                      let successInfo = [
                        this.$t('m.system.user.other.synDingTalkSucess'),
                        this.renderTextarea(h, res.result.successInfo.map((v, i) => `${i + 1}. ${v}`).join('\n')),
                      ]
                      if (res.success) {
                        nodes = [
                          ...successInfo,
                          h('br'),
                          this.$t('m.system.user.other.synDingTalkNoError'),
                        ]
                      } else {
                        nodes = [
                          this.$t('m.system.user.other.synDingTalkError'),
                          this.renderTextarea(h, res.result.failInfo.map((v, i) => `${i + 1}. ${v}`).join('\n')),
                          h('br'),
                          ...successInfo,
                        ]
                      }
                      return nodes
                    }
                  }
                }
                if (res.success) {
                  if (options != null) {
                    this.$success(options)
                  } else {
                    this.$message.success(res.message)
                  }
                  //this.$emit('sync-ok')
                } else {
                  if (options != null) {
                    this.$warning(options)
                  } else {
                    this.$message.warning(res.message)
                  }
                  //this.$emit('sync-error')
                }
              }).catch(() => model.destroy()).finally(() => {
                resolve()
                this.loadData()
                /*this.$emit('sync-finally', {
                  type,
                  direction,
                  isToApp: direction === '/toApp',
                  isToLocal: direction === '/toLocal',
                })*/
              })
            },
            onCancel() {
              resolve()
            },
          })
        })
      },
      renderTextarea(h, value) {
        return h('a-textarea', {
          props: {
            value: value,
            readOnly: true,
            autosize: {minRows: 5, maxRows: 10},
          },
          style: {
            // 关闭textarea的自动换行，使其可以左右滚动
            whiteSpace: 'pre',
            overflow: 'auto',
          }
        })
      },
    },
    watch: {
      deptId: {
        handler(value) {
          if (value) {
            this.url.list = this.url.listInit + '&deptId=' + value
          } else {
            this.url.list = this.url.listInit
          }
          this.loadData()
        },
        immediate: true
      }
    }
  }
</script>
<style lang="less" scoped>

</style>
